﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using NLog;

namespace ConsoleService
{
    static class Program
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            ServerMonitor.RunAsService = false;
            ServerMonitor.CanRun = true;
            var args = Environment.GetCommandLineArgs();
            var entryAssembly = System.Reflection.Assembly.GetEntryAssembly().Location;
            var processname = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location);
            var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;
            if (exists)
            {
                logger.Error("Another instance of the application is already running.");
            }
            else
            {
                foreach (var arg in args)
                {
                    if (arg.Trim().Equals("--service", StringComparison.InvariantCultureIgnoreCase))
                    {
                        ServerMonitor.RunAsService = true;
                    }
                }
                logger.Info("Starting as a service: {0}", ServerMonitor.RunAsService);
                if (ServerMonitor.RunAsService)
                {
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[] 
                    { 
                        new ServerService() 
                    };
                    ServiceBase.Run(ServicesToRun);
                }
                else
                {
                    var wnd = new ServerServiceForm();
                    var restarter = new ServerService();
                    restarter.StartService(null);
                    wnd.ShowDialog();
                    restarter.StopService();
                    logger.Info("Program is terminating");
                }
            }
        }
    }
}
